package com.change.service.company;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.change.core.page.Page;
import com.change.dto.req.QueryCompanyInfoReq;
import com.change.dto.req.SaveAccountInfoReq;
import com.change.dto.req.SaveCompanyInfoReq;
import com.change.dto.resp.QueryCompanyInfoResp;
import com.change.entity.company.CompanyInfo;
import com.change.entity.relation.AccountCompanyRelation;
import com.change.mapper.account.AccountInfoMapper;
import com.change.mapper.company.CompanyInfoMapper;
import com.change.mapper.relation.AccountCompanyRelationMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

/**
 * @author 坏孩子是你啊
 * @date 2022-08-15
 */
@Slf4j
@Service
public class CompanyInfoService extends ServiceImpl<CompanyInfoMapper, CompanyInfo> {
    private final CompanyInfoMapper companyInfoMapper;
    private final AccountInfoMapper accountInfoMapper;
    private final AccountCompanyRelationMapper relationMapper;

    public CompanyInfoService(CompanyInfoMapper companyInfoMapper,
                              AccountInfoMapper accountInfoMapper,
                              AccountCompanyRelationMapper relationMapper) {
        this.companyInfoMapper = companyInfoMapper;
        this.accountInfoMapper = accountInfoMapper;
        this.relationMapper = relationMapper;
    }

    public Page<List<QueryCompanyInfoResp>> getPage(Page page, QueryCompanyInfoReq req) {
        page.offset();
        List<QueryCompanyInfoReq> records = this.companyInfoMapper.pageCompany(page, req);
        page.setRecords(records);
        long total = this.companyInfoMapper.pageCompanyTotal(req);
        page.setTotal(total);
        return page;
    }

    public QueryCompanyInfoResp detail(Integer id) {
        QueryCompanyInfoResp companyResp = this.companyInfoMapper.detailCompanyById(id);
        return companyResp;
    }

    @Transactional(rollbackFor = Exception.class)
    public CompanyInfo save(SaveAccountInfoReq accountReq, SaveCompanyInfoReq companyReq) {


        // 申请注册公司
        CompanyInfo companyInfo = new CompanyInfo();
        // 设置公司账户/标识：yyyyMMddHHmmss + 001
        String companyAccounts =
                DateUtil.format(LocalDateTime.now(), "yyyyMMddHHmmss") + "001";
        companyInfo.setCompanyAccounts(companyAccounts);
        BeanUtil.copyProperties(companyReq, companyInfo);
        this.companyInfoMapper.insert(companyInfo);

        Integer companyId = companyInfo.getId();
        log.info("注册的公司id：{}", companyId);

        Integer accountId = accountReq.getId();
        // 该用户虽然可以关联多个公司，自己申请注册公司的时候绝对是木有滴
        AccountCompanyRelation hasRelation =
                this.relationMapper.queryRelationByIds(accountId, companyId);
        // null 时添加申请的关联关系
        if (Objects.isNull(hasRelation)) {
            // 申请注册公司的用户关联起来
            AccountCompanyRelation relation = new AccountCompanyRelation();
            relation.setCompanyId(companyId);
            relation.setAccountId(accountId);
            this.relationMapper.insert(relation);
        }
        return companyInfo;
    }

    @Transactional(rollbackFor = Exception.class)
    public CompanyInfo update(SaveCompanyInfoReq req) {
        CompanyInfo companyInfo = new CompanyInfo();
        BeanUtil.copyProperties(req, companyInfo);
        this.companyInfoMapper.updateById(companyInfo);
        return companyInfo;
    }

    /**
     * 逻辑删除：企业信息
     *
     * @param id 公司ID
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public Integer delete(Integer id) {
        CompanyInfo companyInfo = this.companyInfoMapper.selectById(id);
        companyInfo.setDeleted(1);
        return this.companyInfoMapper.updateById(companyInfo);
    }

    /**
     * 审核
     */
    @Transactional(rollbackFor = Exception.class)
    public Integer audit(Integer id) {
        CompanyInfo companyInfo = this.companyInfoMapper.selectById(id);
        // enabled == true ? 启用（审核通过） : 禁用（审核未通过）
        boolean flag = companyInfo.getEnabled() == true ? false : true;
        companyInfo.setEnabled(flag);
        return this.companyInfoMapper.updateById(companyInfo);
    }
}
